﻿@using System.Data.SqlServerCe
@using System.Xml.Linq
@using Microsoft.Web.Helpers
@using Resources
@{
    Check.User(Can.ManageWidgets);

    var formId = UrlData[0].AsInt();
    var activeLayerId = UrlData[1].AsInt();
    var db = Database.Open((string)App.Database);
    var zoneId = 0;
    var layerId = 0;
    var displayOrder = 0;
    var widgetId = 0;
    var formName = string.Empty;
    var legend = string.Empty;
    var fromAddress = string.Empty;
    var toAddress = string.Empty;
    var subject = string.Empty;
    var beforeSendMessage = string.Empty;
    var sendMessage = string.Empty;
    var sendErrorMessage = string.Empty;
    var showFormAfterSending = false;
    var smtpServer = string.Empty;
    var smtpPort = 25;
    var smtpUserName = string.Empty;
    var smtpPassword = string.Empty;
    var smtpEnableSsl = false;

    var commandText = @"SELECT WidgetId, Forms.FormName, Legend, FromAddress, ToAddress, Subject,
                        BeforeSendMessage, SendMessage, SendErrorMessage, ShowFormAfterSending,
                        SmtpServer, SmtpPort, SmtpUserName, SmtpPassword, SmtpEnableSsl,
                        ZoneId, Widgets.LayerId, DisplayOrder, Layout FROM Forms 
                        INNER JOIN Widgets ON Forms.FormId = Widgets.FormId 
                        INNER JOIN Layers ON Widgets.LayerId = Layers.LayerId 
                        WHERE Forms.FormId = @0";

    var form = db.QuerySingle(commandText, formId);
    
    if (form != null) {
        zoneId = form.ZoneId;
        layerId = form.LayerId;
        displayOrder = form.DisplayOrder;
        widgetId = form.WidgetId;
        formName = form.FormName;
        legend = form.Legend;
        fromAddress = form.FromAddress;
        toAddress = form.ToAddress;
        subject = form.Subject;
        beforeSendMessage = form.BeforeSendMessage;
        sendMessage = form.SendMessage;
        sendErrorMessage = form.SendErrorMessage;
        showFormAfterSending = form.ShowFormAfterSending;
        smtpServer = form.SmtpServer;
        smtpPort = form.SmtpPort;
        smtpUserName = form.SmtpUserName;
        smtpPassword = form.SmtpPassword;
        smtpEnableSsl = form.SmtpEnableSsl;
    }
    else {
        Response.Redirect("~/Admin/");
    }

    var yesno = new List<SelectListItem> {
        new SelectListItem { Value = "True", Text = "Yes" },
        new SelectListItem { Value = "False", Text = "No" },
    };

    commandText = @"SELECT LayerId, LayerName FROM Layers WHERE Layout = @0";
    var layers = db.Query(commandText, (string)form.Layout).Select(l => new SelectListItem {
        Value = l.LayerId.ToString(),
        Text = l.LayerName,
        Selected = l.LayerId == activeLayerId
    });

    string path = Server.MapPath(Themes.GetResourcePath("Zones", Path.GetFileNameWithoutExtension(form.Layout) + ".xml"));
    var xml = XDocument.Load(path);

    var zones = xml.Descendants("zone").Select(z => new SelectListItem {
        Value = z.Element("id").Value,
        Text = z.Element("name").Value,
        Selected = z.Element("id").Value == form.ZoneId.ToString()
    });

    Validation.Add("LayerId", Validator.Required(), Validator.Regex(@"^\d*$", "Must be a number"));
    Validation.Add("ZoneId", Validator.Required(), Validator.Regex(@"^\d*$", "Must be a number"));
    Validation.Add("DisplayOrder", Validator.Regex(@"^\d*$", "Must be a number"));

    if (IsPost && Validation.IsValid()) {
        zoneId = Request["ZoneId"].AsInt();
        layerId = Request["LayerId"].AsInt();
        displayOrder = Request["DisplayOrder"].AsInt();
        var theme = Themes.CurrentTheme;
        commandText = @"UPDATE Widgets SET ZoneId = @0, LayerId = @1, DisplayOrder = @2, Theme = @3 WHERE WidgetId = @4";
        db.Execute(commandText, zoneId, layerId, displayOrder, theme, widgetId);
        
        formName = Request["FormName"];
        legend = Request["Legend"];
        smtpServer = Request["SmtpServer"];
        smtpPort = Request["SmtpPort"].AsInt();
        smtpUserName = Request["SmtpUserName"];
        smtpPassword = Request["SmtpPassword"];
        fromAddress = Request["FromAddress"];
        smtpEnableSsl = Request["SmtpSsl"].IsOn();
        subject = Request["Subject"];
        toAddress = Request["ToAddress"];
        beforeSendMessage = Request.Unvalidated("BeforeSendMessage");
        sendMessage = Request.Unvalidated("SendMessage");
        sendErrorMessage = Request.Unvalidated("SendErrorMessage");
        showFormAfterSending = Request["ShowForm"].IsOn();
        commandText = @"UPDATE Forms SET FormName = @0, Legend = @1, SmtpServer = @2, SmtpPort = @3, SmtpUserName = @4, SmtpPassword = @5, FromAddress = @6, 
                        SmtpEnableSsl = @7, Subject = @8, ToAddress = @9, BeforeSendMessage = @10, SendMessage = @11, SendErrorMessage = @12, ShowFormAfterSending = @13 WHERE FormId = @14";
        try {
            db.Execute(commandText, formName, legend, smtpServer, smtpPort, smtpUserName, smtpPassword, fromAddress, smtpEnableSsl, subject, toAddress, beforeSendMessage, sendMessage, sendErrorMessage, showFormAfterSending, formId);
            Response.Redirect("~/Admin/Widgets/ManageWidgets/" + activeLayerId);
        }
        catch (SqlCeException ex) {
            if (ex.Message.StartsWith("A duplicate value")) {
                ModelState.AddError("FormName", "This is a duplicate of an existing form name. The form name must be unique.");
            }
        }
    }
}
<form method="post">
    <fieldset>
        <legend>Manage Form Widget</legend>
        @ControlGroup.DropDownList("Select Layer: ", "LayerId", layers, " --Select Layer-- ", layerId)
        @ControlGroup.DropDownList("Select Zone: ", "ZoneId", zones, " --Select Zone-- ", zoneId)
        @ControlGroup.TextBox("Display Order: ", "DisplayOrder", displayOrder.ToString(), new { style = "width: 20px" })
        @ControlGroup.TextBox("Form Name: ", "FormName", formName)
        @ControlGroup.TextBox("Legend: ", "Legend", legend, helperText: AdminResource.FormWidgetLegendHelpText)
        @ControlGroup.TextBox("Subject: ", "Subject", subject, new { style="width:100%;" })
        @ControlGroup.TextBox("Email From Address: ", "FromAddress", fromAddress)
        @ControlGroup.TextBox("Email To Address: ", "ToAddress", toAddress)
        @ControlGroup.TextArea("Message before sending:", "BeforeSendMessage", beforeSendMessage, new { @class = "ckeditor" }, AdminResource.FormWidgetBeforeSendMessageHelpText)
        @ControlGroup.TextArea("Message after sending:", "SendMessage", sendMessage, new { @class = "ckeditor" }, AdminResource.FormWidgetSendMessageHelpText)
        @ControlGroup.TextArea("Message in event of sending error:", "SendErrorMessage", sendErrorMessage, new { @class = "ckeditor" }, AdminResource.FormWidgetSendErrorMessageHelpText)
        @ControlGroup.RadioButtonGroup("Show Form After Sending?", "ShowForm", yesno, showFormAfterSending.ToString(), AdminResource.FormWidgetShowAfterSendingHelpText, true)
        @ControlGroup.TextBox("SMTP Server Address: ", "SmtpServer", smtpServer, helperText: AdminResource.FormWidgetSmtpServerHelpText)
        @ControlGroup.TextBox("SMTP Port: ", "SmtpPort", smtpPort.ToString())
        @ControlGroup.TextBox("SMTP User Name: ", "SmtpUserName", smtpUserName)
        @ControlGroup.TextBox("SMTP Password: ", "SmtpPassword", smtpPassword)
        @ControlGroup.RadioButtonGroup("Use SSL?", "SmtpSsl", yesno, smtpEnableSsl.ToString(), inline: true)
        @ControlGroup.Button()
    </fieldset>
</form>
@section Script{
    <script type="text/javascript" src="/Scripts/ckeditor/ckeditor.js"></script>
}